package com.Dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.database.Mysql;
import com.news.model.User;

import java.util.ArrayList;
import java.util.List;

public class UserDao {
    private SQLiteOpenHelper dbHelper;

    public UserDao(Context context) {
        dbHelper = new Mysql(context); // 假设您有一个UserDBHelper类
    }

    // 插入用户
    public long insertUser(User user) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("password", user.getPassword()); // 加密后的密码
        values.put("name", user.getName());

        long rowId = db.insert("users", null, values);
        db.close(); // 插入后关闭数据库连接
        return rowId;
    }
    public boolean checkLogin(String username, String password) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String query = "SELECT * FROM users WHERE name = ? AND password = ?";

        Cursor cursor = db.rawQuery(query, new String[]{username, password});
        try {
            if (cursor.moveToFirst()) {
                // 如果找到了匹配的记录
                return true;
            }
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
        }
        // 如果没有找到匹配的记录
        return false;
    }
    //查询指定用户是否存在
    public boolean checkUserExists(String username) {
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = dbHelper.getReadableDatabase();
            // 假设用户表名为"users"，用户名字段名为"username"
            String query = "SELECT * FROM users WHERE name = ?";
            cursor = db.rawQuery(query, new String[]{username});

            // 如果cursor不为空且至少有一条记录，则用户名存在
            return cursor != null && cursor.moveToFirst();
        } catch (Exception e) {
            Log.e("Database", "Error checking user existence", e);
            // 在这里可以添加更详细的错误处理逻辑
            return false;
        } finally {
            // 关闭Cursor和Database，确保资源得到释放
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
            if (db != null && db.isOpen()) {
                db.close();
            }
        }
    }
    // 查询所有用户
    public List<User> getAllUsers() {
        List<User> userList = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query("users", null, null, null, null, null, null);

        if (cursor.moveToFirst()) {
            do {
                User user = new User();
                int userIdIndex = cursor.getColumnIndex("userid");
                int passwordIndex = cursor.getColumnIndex("password");
                int nameIndex = cursor.getColumnIndex("name");
                int avatarUrlIndex = cursor.getColumnIndex("avatar_url");

                if (userIdIndex != -1) {
                    user.setUserId(cursor.getInt(userIdIndex));
                }
                if (passwordIndex != -1) {
                    user.setPassword(cursor.getString(passwordIndex)); // 这里应该是解密后的密码
                }
                if (nameIndex != -1) {
                    user.setName(cursor.getString(nameIndex));
                }
                if (avatarUrlIndex != -1) {
                    user.setAvatarUrl(cursor.getString(avatarUrlIndex));
                }

                userList.add(user);
            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close(); // 查询后关闭数据库连接
        return userList;
    }

    //
    // 根据 userId 获取用户信息
    public User getUserById(int userId){
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = null;
        User user = null;

        try{
            cursor = db.query("users", null, "userid = ?", new String[]{String.valueOf(userId)}, null, null, null);
            if(cursor != null && cursor.moveToFirst()){
                user = new User();

                int userIdIndex = cursor.getColumnIndex("userid");
                if (userIdIndex != -1) {
                    user.setUserId(cursor.getInt(userIdIndex));
                }

                int passwordIndex = cursor.getColumnIndex("password");
                if (passwordIndex != -1) {
                    user.setPassword(cursor.getString(passwordIndex)); // 解密后的密码
                }

                int nameIndex = cursor.getColumnIndex("name");
                if (nameIndex != -1) {
                    user.setName(cursor.getString(nameIndex));
                }

                int avatarUrlIndex = cursor.getColumnIndex("avatar_url");
                if (avatarUrlIndex != -1) {
                    user.setAvatarUrl(cursor.getString(avatarUrlIndex));
                }
            }
        } catch (Exception e){
            Log.e("Database", "Error fetching user by userId", e);
        } finally {
            {
                if(cursor != null && !cursor.isClosed()){
                    cursor.close();
                }
                db.close();
            }
            return user;
        }
    }

    // 根据用户名获取用户信息
    public User getUserByName(String username) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = null;
        User user = null;

        try {
            cursor = db.query("users", null, "name = ?", new String[]{username}, null, null, null);

            if (cursor != null && cursor.moveToFirst()) {
                user = new User();

                int userIdIndex = cursor.getColumnIndex("userid");
                if (userIdIndex != -1) {
                    user.setUserId(cursor.getInt(userIdIndex));
                }

                int passwordIndex = cursor.getColumnIndex("password");
                if (passwordIndex != -1) {
                    user.setPassword(cursor.getString(passwordIndex)); // 解密后的密码
                }

                int nameIndex = cursor.getColumnIndex("name");
                if (nameIndex != -1) {
                    user.setName(cursor.getString(nameIndex));
                }

                int avatarUrlIndex = cursor.getColumnIndex("avatar_url");
                if (avatarUrlIndex != -1) {
                    user.setAvatarUrl(cursor.getString(avatarUrlIndex));
                }
            }
        } catch (Exception e) {
            Log.e("Database", "Error fetching user by username", e);
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
            db.close(); // 查询后关闭数据库连接
        }

        return user;
    }


    // 更新用户（根据user_id）
    public int updateUser(User user) {
        // ... 实现更新逻辑 ...
        return 0; // 示例返回0，实际应根据更新结果返回
    }

    // 删除用户（根据user_id）
    public void deleteUser(int userId) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete("users", "userid = ?", new String[]{String.valueOf(userId)});
        db.close(); // 删除后关闭数据库连接
    }
}
// UserDBHelper类（您应该有一个这样的
